package com.wyzz.hr.action;

import java.io.FileInputStream;
import java.math.BigDecimal;
import java.util.List;
import org.apache.commons.lang.StringUtils;
import org.hibernate.FetchMode;
import org.hibernate.criterion.DetachedCriteria;

import com.wyzz.hr.bo.IBenefitTypeBO;
import com.wyzz.hr.bo.IEmpBenefitBo;
import com.wyzz.hr.bo.IEmpSalaryAcctitemsBo;
import com.wyzz.hr.bo.IEmployeeBo;
import com.wyzz.hr.bo.ISalaryconfBo;
import com.wyzz.hr.pojo.Empbenefit;
import com.wyzz.hr.pojo.Employee;
import com.wyzz.hr.pojo.Empsalaryconfig;
import com.wyzz.hr.pojo.Emptype;
import com.wyzz.hr.pojo.Location;
import com.wyzz.hr.spring.SpringBeanFactory;
import com.wyzz.hr.util.BaseCrit;
import com.wyzz.hr.util.DateUtil;
import com.wyzz.hr.util.Pager;

public class SearchEmpbenefit extends CompAction {

	public SearchEmpbenefit() {
		page = new Pager();
		emp = new Employee();
		searchOrExport = null;
		docStream = null;
		contentDisposition = null;
		serverFileName = null;
		employee = new Employee();
		employee.setEmpStatus(Integer.valueOf(1));
	}

	public String execute() throws Exception {
		getDrillDownList();
		empbenefitList = searchEmpBenefit();
		ISalaryconfBo salaryconfBo = (ISalaryconfBo) SpringBeanFactory
				.getBean("salaryconfBo");
		salaryconfBo.calcSalaryConfByTypes(empbenefitList);
		if ("export".equals(searchOrExport))
			return downloadToExcel(empbenefitList, "OEmpSalaryBenefit",
					outmatchModelId, "");
		else
			return "success";
	}

	private List searchEmpBenefit() {
		DetachedCriteria dcEmpBenefit = searchEmpBenefit_DC();
		addCriteria(dcEmpBenefit);
		IEmpBenefitBo empbenefitBo = (IEmpBenefitBo) getBean("empbenefitBo");
		return empbenefitBo.findEmpBenefit(dcEmpBenefit, page, searchOrExport);
	}

	private DetachedCriteria searchEmpBenefit_DC() {
		DetachedCriteria dc = DetachedCriteria.forClass(Employee.class);
		dc.setFetchMode(Employee.PROP_EMP_DEPT_NO, FetchMode.JOIN);
		dc.setFetchMode(Employee.PROP_EMP_LOCATION_NO, FetchMode.JOIN);
		dc.setFetchMode(Employee.PROP_EMP_TYPE, FetchMode.JOIN);
		dc.setFetchMode(Employee.PROP_EMP_BENEFIT_TYPE, FetchMode.JOIN);
		dc.createAlias(Employee.PROP_CONFIG, "config", 1);
		dc.createAlias(Employee.PROP_EMP_PB_NO, "empPbNo", 1);
		dc.createAlias(Employee.PROP_EMP_BENEFIT, "benefit", 1);
		return dc;
	}

	private void addCriteria(DetachedCriteria dc) {
		if ("SUB".equals(super.authorityCondition))
			addSubDC(dc, "", 2);
		if ("SUB".equals(super.authorityCondition))
			addSubDC(dc, "", 2);
		addOrders(dc, page, new String[] {
				(new StringBuilder()).append("benefit.").append(
						Empbenefit.PROP_EBF_EBFSTARTMONTH).append("-down")
						.toString(),
				(new StringBuilder()).append(Employee.PROP_EMP_DISTINCT_NO)
						.append("-up").toString() });
		BaseCrit.addEmpDC(dc, null, empNameOrDist);
		BaseCrit.addDC(dc, Employee.PROP_EMP_DISTINCT_NO, "like",
				new String[] { employee.getEmpDistinctNo() });
		BaseCrit.addDC(dc, Employee.PROP_EMP_NAME, "like",
				new String[] { employee.getEmpName() });
		BaseCrit.addDeptDC(dc, Employee.PROP_EMP_DEPT_NO,
				Employee.PROP_EMP_PB_NO, Integer.valueOf(1), employee
						.getEmpDeptNo());
		BaseCrit.addDC(dc, Employee.PROP_EMP_STATUS, "eq",
				new Integer[] { employee.getEmpStatus() });
		BaseCrit.addDC(dc, Employee.PROP_EMP_TYPE, Emptype.PROP_ID,
				new Object[] { employee.getEmpType() });
		BaseCrit.addDC(dc, Employee.PROP_EMP_LOCATION_NO, Location.PROP_ID,
				new Object[] { employee.getEmpLocationNo() });
		BaseCrit.addDC(dc, Employee.PROP_EMP_BENEFIT_TYPE, "id",
				new Object[] { employee.getEmpBenefitType() });
		if (employee.getEmpIdentificationNo() != null
				&& employee.getEmpIdentificationNo().length() > 0) {
			BaseCrit.addDC(dc, Employee.PROP_EMP_IDENTIFICATION_TYPE, "eq",
					new Integer[] { new Integer(0) });
			BaseCrit.addDC(dc, Employee.PROP_EMP_IDENTIFICATION_NO, "like",
					new String[] { employee.getEmpIdentificationNo() });
		}
		if (employee.getBenefit() != null) {
			BaseCrit.addDC(dc, (new StringBuilder()).append("benefit.").append(
					Empbenefit.PROP_EBF_EBFSTARTMONTH).toString(), "like",
					new String[] { employee.getBenefit().getEbfStartMonth() });
			BaseCrit.addDC(dc, (new StringBuilder()).append("benefit.").append(
					Empbenefit.PROP_EBF_EBFPENSIONNO).toString(), "like",
					new String[] { employee.getBenefit().getEbfPensionNo() });
			BaseCrit.addDC(dc, (new StringBuilder()).append("benefit.").append(
					Empbenefit.PROP_EBF_EBFHOUSINGNO).toString(), "like",
					new String[] { employee.getBenefit().getEbfHousingNo() });
			BaseCrit.addDC(dc, (new StringBuilder()).append("benefit.").append(
					Empbenefit.PROP_EBF_EBFMEDICALNO).toString(), "like",
					new String[] { employee.getBenefit().getEbfMedicalNo() });
		}
		if (!StringUtils.isEmpty(amountCategory))
			if ("pension".equals(amountCategory))
				BaseCrit.addDC(dc, (new StringBuilder()).append("benefit.")
						.append(Empbenefit.PROP_EBF_EBFPENSIONAMOUNT)
						.toString(), "between", new BigDecimal[] {
						new BigDecimal(amountFrom), new BigDecimal(amountTo) });
			else if ("house".equals(amountCategory))
				BaseCrit.addDC(dc, (new StringBuilder()).append("benefit.")
						.append(Empbenefit.PROP_EBF_EBFINSURANCEAMOUNT)
						.toString(), "between", new BigDecimal[] {
						new BigDecimal(amountFrom), new BigDecimal(amountTo) });
			else if ("insurance".equals(amountCategory))
				BaseCrit.addDC(dc, (new StringBuilder()).append("benefit.")
						.append(Empbenefit.PROP_EBF_EBFMEDICALNO).toString(),
						"between", new BigDecimal[] {
								new BigDecimal(amountFrom),
								new BigDecimal(amountTo) });
	}

	private void getDrillDownList() {
		locationList = getDrillDown("Location", new String[0]);
		empTypeList = getDrillDown("EmpType", new String[0]);
		ebfTypeList = getDrillDown("BenefitType", new String[0]);
		empStatus = getDrillDown("EmpStatus", new String[0]);
		year = DateUtil.formatTodayToS("yyyy");
		month = DateUtil.formatTodayToS("MM");
	}

	public String addBenefitInit() throws Exception {
		if (StringUtils.isEmpty(employeeId)) {
			addErrorInfo(msgNoEmp, new Object[] { "noemp" });
			return "input";
		}
		String fetch[] = { Employee.PROP_EMP_BENEFIT_TYPE,
				Employee.PROP_EMP_BENEFIT, Employee.PROP_EMP_DEPT_NO,
				Employee.PROP_EMP_LOCATION_NO, Employee.PROP_EMP_PB_NO,
				Employee.PROP_EMP_TYPE };
		IEmployeeBo empBo = (IEmployeeBo) getBean("empBo");
		emp = empBo.loadEmp(employeeId, fetch);
		if (emp == null) {
			addErrorInfo(msgNoEmp, new Object[] { "noemp" });
			return "input";
		}
		if (emp.getBenefit() != null) {
			addErrorInfo(msghasBenefit, new Object[] { "hasbenefit",
					emp.getEmpName() });
			return "input";
		} else {
			startBtfYear = DateUtil.formatTodayToS("yyyy");
			startBtfMonth = DateUtil.formatTodayToS("MM");
			ebfTypeList = getDrillDown("BenefitType", new String[0]);
			yearList = getDrillDown("EmpSalaryPeriod", new String[0]);
			return "success";
		}
	}

	public String addNewBenefit() throws Exception {
		if (emp.getBenefit().getEbfHousingAmount() == null
				&& emp.getBenefit().getEbfInsuranceAmount() == null
				&& emp.getBenefit().getEbfPensionAmount() == null) {
			addErrorInfo(msgNoBaseErr, new Object[] { "nobasep" });
			return "input";
		}
		Empsalaryconfig config = loadConfig(employeeId, null);
		if (config == null) {
			addErrorInfo(msgNoEmp, new Object[] { "noemp" });
			return "input";
		}
		if (config.getEmployee().getBenefit() != null) {
			addErrorInfo(msghasBenefit, new Object[] { "hasbenefit",
					config.getEmployee().getEmpName() });
			return "input";
		}
		Employee newEmp = config.getEmployee();
		newEmp.setBenefit(emp.getBenefit());
		IBenefitTypeBO bfTypeBo = (IBenefitTypeBO) SpringBeanFactory
				.getBean("benefitTypeBo");
		newEmp.setEmpBenefitType(bfTypeBo.searchById(emp.getEmpBenefitType()
				.getId()));
		newEmp.setEmpLastChangeBy(getCurrentEmp());
		if (config.getId() != null) {
			IEmpSalaryAcctitemsBo esaiBo = (IEmpSalaryAcctitemsBo) SpringBeanFactory
					.getBean("empsalaryacctitemsBo");
			esaiBo.setAcctItemsConfig(new Empsalaryconfig[] { config });
			ISalaryconfBo confBo = (ISalaryconfBo) getBean("salaryconfBo");
			confBo.interpretConfig(new Empsalaryconfig[] { config });
		} else {
			newEmp.setConfig(null);
		}
		IEmpBenefitBo empbenefitBo = (IEmpBenefitBo) getBean("empbenefitBo");
		empbenefitBo.addBenefit(newEmp);
		addSuccessInfo(msgCreateBeneSucc, new Object[] { "SUCC",
				newEmp.getEmpName() });
		return "success";
	}

	public String updateBenefitInit() throws Exception {
		if (StringUtils.isEmpty(employeeId)) {
			addErrorInfo(msgNoEmp, new Object[] { "noemp" });
			return "input";
		}
		String fetch[] = { Employee.PROP_EMP_BENEFIT_TYPE,
				Employee.PROP_EMP_BENEFIT, Employee.PROP_EMP_DEPT_NO,
				Employee.PROP_EMP_LOCATION_NO, Employee.PROP_EMP_PB_NO,
				Employee.PROP_EMP_TYPE };
		IEmployeeBo empBo = (IEmployeeBo) getBean("empBo");
		emp = empBo.loadEmp(employeeId, fetch);
		if (emp == null) {
			addErrorInfo(msgNoEmp, new Object[] { "noemp" });
			return "input";
		}
		if (emp.getBenefit() == null) {
			addErrorInfo(msgNoBenefit, new Object[] { "nobenefit",
					emp.getEmpName() });
			return "input";
		} else {
			ISalaryconfBo salaryBo = (ISalaryconfBo) getBean("salaryconfBo");
			benefitValue = salaryBo.findSalaryBenefitValue(employeeId);
			IEmpBenefitBo empbenefitBo = (IEmpBenefitBo) getBean("empbenefitBo");
			BenefitList = empbenefitBo.searchByEmpNo(employeeId);
			benefitPayvalueList = empbenefitBo.searchbenefitpayvalueByEmpId(emp
					.getId());
			String YearOrMonth = emp.getBenefit().getEbfStartMonth();
			startBtfYear = YearOrMonth.substring(0, 4);
			startBtfMonth = YearOrMonth.substring(4, 6);
			ebfTypeList = getDrillDown("BenefitType", new String[0]);
			yearList = getDrillDown("EmpSalaryPeriod", new String[0]);
			return "success";
		}
	}

	public String updateBenefit() throws Exception {
		if (emp.getBenefit().getEbfHousingAmount() == null
				&& emp.getBenefit().getEbfInsuranceAmount() == null
				&& emp.getBenefit().getEbfPensionAmount() == null) {
			addErrorInfo(msgNoBaseErr, new Object[] { "nobasep" });
			return "input";
		}
		Empsalaryconfig config = loadConfig(employeeId, null);
		if (config == null) {
			addErrorInfo(msgNoEmp, new Object[] { "noemp" });
			return "input";
		}
		if (config.getEmployee().getBenefit() == null) {
			addErrorInfo(msgNoBenefit, new Object[] { "nobenefit",
					config.getEmployee().getEmpName() });
			return "input";
		}
		IEmpBenefitBo empbenefitBo = (IEmpBenefitBo) getBean("empbenefitBo");
		Empbenefit oldBenefit = empbenefitBo.loadPrevBenefit(employeeId);
		if (oldBenefit != null
				&& emp.getBenefit().getEbfStartMonth().compareTo(
						oldBenefit.getEbfStartMonth()) < 0) {
			addErrorInfo(msgStartYMTooEarly, new Object[] { "tooearly" });
			return "input";
		}
		Employee newEmp = config.getEmployee();
		emp.getBenefit().setEbfId(newEmp.getBenefit().getEbfId());
		newEmp.setBenefit(emp.getBenefit());
		IBenefitTypeBO bfTypeBo = (IBenefitTypeBO) SpringBeanFactory
				.getBean("benefitTypeBo");
		newEmp.setEmpBenefitType(bfTypeBo.searchById(emp.getEmpBenefitType()
				.getId()));
		newEmp.setEmpLastChangeBy(getCurrentEmp());
		if (config.getId() != null) {
			IEmpSalaryAcctitemsBo esaiBo = (IEmpSalaryAcctitemsBo) SpringBeanFactory
					.getBean("empsalaryacctitemsBo");
			esaiBo.setAcctItemsConfig(new Empsalaryconfig[] { config });
			ISalaryconfBo confBo = (ISalaryconfBo) getBean("salaryconfBo");
			confBo.interpretConfig(new Empsalaryconfig[] { config });
		} else {
			newEmp.setConfig(null);
		}
		empbenefitBo.updateBenefit(oldBenefit, newEmp);
		addSuccessInfo(msgUpdBeneSucc, new Object[] { "SUCC",
				newEmp.getEmpName() });
		return "success";
	}

	public String delEmpbenefit() throws Exception {
		if (StringUtils.isEmpty(employeeId) || StringUtils.isEmpty(ebfId)) {
			addErrorInfo("\u53C2\u6570\u9519\u8BEF\uFF0C\u8BF7\u5237\u65B0\u540E\u91CD\u8BD5\uFF01");
			return "input";
		}
		IEmployeeBo empBo = (IEmployeeBo) getBean("empBo");
		Employee empl = empBo.loadEmp(employeeId, new String[] { "benefit" });
		if (empl == null || empl.getBenefit() == null
				|| StringUtils.isEmpty(empl.getBenefit().getEbfId())
				|| !StringUtils.equals(empl.getBenefit().getEbfId(), ebfId)) {
			addErrorInfo("\u53C2\u6570\u9519\u8BEF\uFF0C\u8BF7\u5237\u65B0\u540E\u91CD\u8BD5\uFF01");
			return "input";
		}
		IEmpBenefitBo empbenefitBo = (IEmpBenefitBo) getBean("empbenefitBo");
		String error = empbenefitBo.deleteBenefit(empl, ebfId,
				getCurrentEmpNo());
		if (StringUtils.isNotEmpty(error))
			addErrorInfo(error);
		else
			addSuccessInfo((new StringBuilder()).append("\u5220\u9664").append(
					empl.getEmpName()).append(
					"\u7684\u793E\u4FDD\u8BB0\u5F55\u6210\u529F\u3002")
					.toString());
		return "success";
	}

	/**
	 * @deprecated Method initAddPageData is deprecated
	 */

	public String initAddPageData() {
		if (StringUtils.isEmpty(employeeId)) {
			addErrorInfo(msgNoEmp, new Object[] { "noemp" });
			return "input";
		}
		String fetch[] = {
				Employee.PROP_EMP_BENEFIT_TYPE,
				Employee.PROP_EMP_BENEFIT,
				Employee.PROP_EMP_DEPT_NO,
				Employee.PROP_EMP_LOCATION_NO,
				Employee.PROP_EMP_PB_NO,
				Employee.PROP_EMP_TYPE,
				Employee.PROP_CONFIG,
				(new StringBuilder()).append(Employee.PROP_CONFIG).append(".")
						.append(Empsalaryconfig.PROP_ESC_JOBGRADE).toString(),
				(new StringBuilder()).append(Employee.PROP_CONFIG).append(".")
						.append(Empsalaryconfig.PROP_ESC_ESAV_ID).toString() };
		IEmployeeBo empBo = (IEmployeeBo) getBean("empBo");
		emp = empBo.loadEmp(employeeId, fetch);
		if (emp == null) {
			addErrorInfo(msgNoEmp, new Object[] { "noemp" });
			return "input";
		}
		if (emp.getBenefit() != null) {
			addActionError("\u8BE5\u5458\u5DE5\u5DF2\u7ECF\u5B58\u5728\u793E\u4FDD\u8BB0\u5F55\uFF01");
			return "input";
		}
		if (benefit == null)
			benefit = new Empbenefit();
		startBtfYear = DateUtil.formatTodayToS("yyyy");
		startBtfMonth = DateUtil.formatTodayToS("MM");
		getAllDrillDown();
		return null;
	}

	public void getAllDrillDown() {
		ebfTypeList = getDrillDown("BenefitType", new String[0]);
		yearList = getDrillDown("EmpSalaryPeriod", new String[0]);
	}

	public Pager getPage() {
		return page;
	}

	public void setPage(Pager page) {
		this.page = page;
	}

	public List getEmpbenefitList() {
		return empbenefitList;
	}

	public void setEmpbenefitList(List empbenefitList) {
		this.empbenefitList = empbenefitList;
	}

	public List getLocationList() {
		return locationList;
	}

	public void setLocationList(List locationList) {
		this.locationList = locationList;
	}

	public List getEmpStatus() {
		return empStatus;
	}

	public void setEmpStatus(List empStatus) {
		this.empStatus = empStatus;
	}

	public String getEmployeeId() {
		return employeeId;
	}

	public void setEmployeeId(String employeeId) {
		this.employeeId = employeeId;
	}

	public Employee getEmp() {
		return emp;
	}

	public void setEmp(Employee emp) {
		this.emp = emp;
	}

	public String[][] getBenefitValue() {
		return benefitValue;
	}

	public void setBenefitValue(String benefitValue[][]) {
		this.benefitValue = benefitValue;
	}

	public static long getSerialVersionUID() {
		return 1L;
	}

	public String getEbfId() {
		return ebfId;
	}

	public void setEbfId(String ebfId) {
		this.ebfId = ebfId;
	}

	public List getBenefitList() {
		return BenefitList;
	}

	public void setBenefitList(List benefitList) {
		BenefitList = benefitList;
	}

	public List getEbfTypeList() {
		return ebfTypeList;
	}

	public void setEbfTypeList(List ebfTypeList) {
		this.ebfTypeList = ebfTypeList;
	}

	public String getInputstartBtfYear() {
		return inputstartBtfYear;
	}

	public void setInputstartBtfYear(String inputstartBtfYear) {
		this.inputstartBtfYear = inputstartBtfYear;
	}

	public String getInputstartBtfMonth() {
		return inputstartBtfMonth;
	}

	public void setInputstartBtfMonth(String inputstartBtfMonth) {
		this.inputstartBtfMonth = inputstartBtfMonth;
	}

	public String getEmpNameOrDist() {
		return empNameOrDist;
	}

	public void setEmpNameOrDist(String empNameOrDist) {
		this.empNameOrDist = empNameOrDist;
	}

	public Employee getEmployee() {
		return employee;
	}

	public void setEmployee(Employee employee) {
		this.employee = employee;
	}

	public List getBenefitPayvalueList() {
		return benefitPayvalueList;
	}

	public void setBenefitPayvalueList(List benefitPayvalueList) {
		this.benefitPayvalueList = benefitPayvalueList;
	}

	public String getSearchOrExport() {
		return searchOrExport;
	}

	public void setSearchOrExport(String searchOrExport) {
		this.searchOrExport = searchOrExport;
	}

	public FileInputStream getDocStream() {
		return docStream;
	}

	public void setDocStream(FileInputStream docStream) {
		this.docStream = docStream;
	}

	public String getContentDisposition() {
		return contentDisposition;
	}

	public void setContentDisposition(String contentDisposition) {
		this.contentDisposition = contentDisposition;
	}

	public String getServerFileName() {
		return serverFileName;
	}

	public void setServerFileName(String serverFileName) {
		this.serverFileName = serverFileName;
	}

	public String getMonth() {
		return month;
	}

	public void setMonth(String month) {
		this.month = month;
	}

	public String getYear() {
		return year;
	}

	public void setYear(String year) {
		this.year = year;
	}

	public List getEmpTypeList() {
		return empTypeList;
	}

	public void setEmpTypeList(List empTypeList) {
		this.empTypeList = empTypeList;
	}

	public String getAmountCategory() {
		return amountCategory;
	}

	public void setAmountCategory(String amountCategory) {
		this.amountCategory = amountCategory;
	}

	public String getAmountFrom() {
		return amountFrom;
	}

	public void setAmountFrom(String amountFrom) {
		this.amountFrom = amountFrom;
	}

	public String getAmountTo() {
		return amountTo;
	}

	public void setAmountTo(String amountTo) {
		this.amountTo = amountTo;
	}

	public List getMonthList() {
		return monthList;
	}

	public void setMonthList(List monthList) {
		this.monthList = monthList;
	}

	public String getStartBtfMonth() {
		return startBtfMonth;
	}

	public void setStartBtfMonth(String startBtfMonth) {
		this.startBtfMonth = startBtfMonth;
	}

	public String getStartBtfYear() {
		return startBtfYear;
	}

	public void setStartBtfYear(String startBtfYear) {
		this.startBtfYear = startBtfYear;
	}

	public List getYearList() {
		return yearList;
	}

	public void setYearList(List yearList) {
		this.yearList = yearList;
	}

	public Empbenefit getBenefit() {
		return benefit;
	}

	public void setBenefit(Empbenefit benefit) {
		this.benefit = benefit;
	}

	public String getEmpBenefitTypeId() {
		return empBenefitTypeId;
	}

	public void setEmpBenefitTypeId(String empBenefitTypeId) {
		this.empBenefitTypeId = empBenefitTypeId;
	}

	public static String getInputIoName() {
		return "IEmpSalaryBenefitUpd";
	}

	public static String getOutputIoName() {
		return "OEmpSalaryBenefit";
	}

	public String getOutmatchModelId() {
		return outmatchModelId;
	}

	public void setOutmatchModelId(String outmatchModelId) {
		this.outmatchModelId = outmatchModelId;
	}

	private static final long serialVersionUID = 1L;
	private Employee employee;
	private String empNameOrDist;
	private List empbenefitList;
	private Pager page;
	private String employeeId;
	private Employee emp;
	private String benefitValue[][];
	private String ebfId;
	List BenefitList;
	private List locationList;
	private List ebfTypeList;
	private List empTypeList;
	private String inputstartBtfYear;
	private String inputstartBtfMonth;
	private String searchOrExport;
	private FileInputStream docStream;
	private String contentDisposition;
	private String serverFileName;
	private String outmatchModelId;
	private List benefitPayvalueList;
	private String year;
	private String month;
	private String amountCategory;
	private String amountFrom;
	private String amountTo;
	private Empbenefit benefit;
	private String empBenefitTypeId;
	private String startBtfYear;
	private String startBtfMonth;
	private List yearList;
	private List monthList;
	public static final String outputIoName = "OEmpSalaryBenefit";
	public static final String inputIoName = "IEmpSalaryBenefitUpd";
}
